package com.demo.product.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Redis分布式锁服务
 * 用于控制秒杀商品库存的并发访问
 */
@Service
public class RedisLockService {

    private static final Logger log = LoggerFactory.getLogger(RedisLockService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String LOCK_PREFIX = "seckill:lock:";
    private static final String UNLOCK_SCRIPT = 
        "if redis.call('get', KEYS[1]) == ARGV[1] then " +
        "return redis.call('del', KEYS[1]) " +
        "else " +
        "return 0 " +
        "end";

    /**
     * 尝试获取分布式锁
     * @param key 锁的key
     * @param expireTime 锁的过期时间（秒）
     * @return 锁的唯一标识，获取失败返回null
     */
    public String tryLock(String key, long expireTime) {
        String lockKey = LOCK_PREFIX + key;
        String lockValue = UUID.randomUUID().toString();
        
        try {
            Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, TimeUnit.SECONDS);
            if (Boolean.TRUE.equals(result)) {
                log.info("获取分布式锁成功，key: {}, value: {}", lockKey, lockValue);
                return lockValue;
            }
        } catch (Exception e) {
            log.error("获取分布式锁异常，key: {}", lockKey, e);
        }
        
        log.warn("获取分布式锁失败，key: {}", lockKey);
        return null;
    }

    /**
     * 释放分布式锁
     * @param key 锁的key
     * @param lockValue 锁的唯一标识
     * @return 释放成功返回true
     */
    public boolean releaseLock(String key, String lockValue) {
        String lockKey = LOCK_PREFIX + key;
        
        try {
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();
            script.setScriptText(UNLOCK_SCRIPT);
            script.setResultType(Long.class);
            
            Long result = redisTemplate.execute(script, Collections.singletonList(lockKey), lockValue);
            boolean success = result != null && result > 0;
            
            if (success) {
                log.info("释放分布式锁成功，key: {}, value: {}", lockKey, lockValue);
            } else {
                log.warn("释放分布式锁失败，key: {}, value: {}", lockKey, lockValue);
            }
            
            return success;
        } catch (Exception e) {
            log.error("释放分布式锁异常，key: {}, value: {}", lockKey, lockValue, e);
            return false;
        }
    }

    /**
     * 检查锁是否存在
     * @param key 锁的key
     * @return 锁存在返回true
     */
    public boolean isLocked(String key) {
        String lockKey = LOCK_PREFIX + key;
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(lockKey));
        } catch (Exception e) {
            log.error("检查锁状态异常，key: {}", lockKey, e);
            return false;
        }
    }
}